using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolObject
{
    private Dictionary<string, List<Object>> _pool = new Dictionary<string, List<Object>>();
    private int _maxCount = 100;
    private Transform _poolParent;

    public PoolObject(int maxCount)
    {
        _maxCount = maxCount;
        if (_poolParent != null)
        {
            return;
        }
        _poolParent = new GameObject("PoolParent").transform;
        _poolParent.gameObject.SetActive(false);
        GameObject.DontDestroyOnLoad(_poolParent.gameObject);
    }

    public void Set(string key, Object obj)
    {
        if (!_pool.ContainsKey(key))
        {
            _pool.Add(key, new List<Object>());
        }
        if (_pool[key].Count >= _maxCount)
        {
            Object.Destroy(obj);
            return;
        }
        if (obj is GameObject)
            (obj as GameObject).transform.SetParent(_poolParent);
        _pool[key].Add(obj);
    }

    public T Get<T>(string key) where T : Object
    {
        if (_pool.ContainsKey(key) && _pool[key].Count > 0)
        {
            Object obj = _pool[key][0];
            _pool[key].RemoveAt(0);
            return obj as T;
        }
        return null;
    }

    public void Clear()
    {
        _pool.Clear();
    }
}
